package com.lhw.ai.service.impl;

import com.alibaba.cloud.ai.advisor.DocumentRetrievalAdvisor;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.embedding.DashScopeEmbeddingOptions;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeCloudStore;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentCloudReader;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeStoreOptions;
import com.alibaba.fastjson.JSON;
import com.lhw.ai.service.BailianService;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.rag.Query;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/**
 * 百炼服务
 *
 * @author: lwh
 * @since: 2025/07/25 13:28:26
 * @version: 1.0
 */
@Service
@Slf4j
public class BailianServiceImpl implements BailianService {

    public static final String INDEX_NAME = "推荐系统知识库";
    @Resource
    private DashScopeApi dashscopeApi;

    /**
     * For bailian call use.
     */
    @Resource
    private ChatClient.Builder builder;


    @Override
    public void uploadFile(String filePath) {

        // 1. import and split documents
        DocumentReader reader = new DashScopeDocumentCloudReader(filePath, dashscopeApi, null);
        List<Document> documentList = reader.get();
        log.info("{} documents loaded and split", documentList.size());
        DashScopeStoreOptions retrieverOptions =
                new DashScopeStoreOptions("推荐系统相关需求知识库");
        retrieverOptions.setEmbeddingOptions(
                DashScopeEmbeddingOptions.builder().withModel("text-embedding-v4").build());
        // 1. add documents to DashScope cloud storage
        VectorStore vectorStore =
                new DashScopeCloudStore(dashscopeApi, new DashScopeStoreOptions("推荐系统知识库"));
        vectorStore.add(documentList);
        log.info("{} documents added to dashscope cloud vector store", documentList.size());
    }

    @Override
    public String queryRag(String queryData) {

        DocumentRetriever retriever = new DashScopeDocumentRetriever(dashscopeApi,
                                                                     DashScopeDocumentRetrieverOptions.builder()
                                                                                                      .withIndexName(
                                                                                                              INDEX_NAME)
                                                                                                      .build());
        // 召回---测试召回，并没有实际使用。
        List<Document> documentList = retriever.retrieve(new Query(
                queryData
        ));

        log.info("documentList: {}", JSON.toJSONString(documentList));

        // 调用大模型，结合召回内容，进行回答分析

        ChatClient chatClient = builder.defaultAdvisors(
                                               new DocumentRetrievalAdvisor(retriever)
                                                       )
                                       .build();

        ChatResponse chatResponse = chatClient.prompt().user(queryData).call().chatResponse();
        log.info("chatResponse: {}", JSON.toJSONString(chatResponse));

        return JSON.toJSONString(chatResponse);
    }
}
